package com.potato369.cryptNacos.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.potato369.cryptNacos.config.BaiduAipConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Objects;

@Api(tags = "UploadController", consumes = "上传文件管理")
@Slf4j
@RestController
@RequestMapping("/data")
public class UploadController {

    private BaiduAipConfig baiduAipConfig;

    @Autowired
    public void setBaiduAipConfig(BaiduAipConfig baiduAipConfig) {
        this.baiduAipConfig = baiduAipConfig;
    }

    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public String upload(@ApiParam(name = "文件数组") @RequestPart MultipartFile[] files) {
        try {
            for (MultipartFile multipartFile : files) {
                byte[] imgData = multipartFile.getBytes();
                String result = String.valueOf(this.baiduAipConfig.aipContentCensor().imageCensorUserDefined(imgData, null));
                JSONObject jsonObject = JSONUtil.parseObj(result);
                log.info("result={}", jsonObject);
                String errorMsg = jsonObject.getStr("error_msg", "");
                if (StrUtil.isNotEmpty(errorMsg)) {
                    return errorMsg;
                }
                Integer conclusionType = jsonObject.getInt("conclusionType");
                if (Objects.equals(conclusionType, 1)) {
                    multipartFile.transferTo(new File("D://tmp//" + UUID.randomUUID() + "." + FileUtil.getSuffix(multipartFile.getOriginalFilename())));
                } else {
                    return jsonObject.getStr("conclusion");
                }
            }
            return "上传成功";
        } catch (Exception e) {
            log.error("上传文件出现错误", e);
            return "上传失败";
        }
    }
}
